
package com.trydofor.id.doer.shell;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.trydofor.aloe.exception.Exceptions;

/**
 * the command to execute
 * 
 * @author : Shi Rongjiu (www.trydofor.com)
 */
public class Command {
    
    /**
     * the arguments
     */
    protected final Map<String, ArgHelp> arghs = new HashMap<String, ArgHelp>();
    
    private final String                 alias;
    private final String                 usage;
    
    /**
     * constructor
     * 
     * @param alias the alias
     * @param usage the usage
     * @throws NullPointerException is name or usage is null
     */
    public Command(String alias, String usage) {
        Exceptions.checkNullPointer(alias);
        Exceptions.checkNullPointer(usage);
        
        this.alias = alias;
        this.usage = usage;
        
        refreshArgs();
    }
    
    /**
     * get the alias of command
     * 
     * @return the alias
     */
    public String getAlias() {
        return alias;
    }
    
    /**
     * get the usage of command
     * 
     * @return the usage
     */
    public String getUsage() {
        return usage;
    }
    
    /**
     * add an argument
     * 
     * @param arg the argument
     * @param args the others arguments
     * @throws NullPointerException if arg is null
     */
    public void addArgument(ArgHelp arg, ArgHelp... args) {
        Exceptions.checkNullPointer(arg);
        arghs.put(arg.getName(), arg);
        for (ArgHelp a : args) {
            arghs.put(a.getName(), a);
        }
    }
    
    /**
     * get the view of all arguments
     * 
     * @return the arguments
     * @see Map#values()
     */
    public Collection<ArgHelp> getArgumentAll() {
        refreshArgs();
        return arghs.values();
    }
    
    /**
     * for subclass, called by constructor and getArgumentAll()
     */
    protected void refreshArgs() {
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(alias);
        sb.append('\n');
        sb.append(usage);
        sb.append('\n');
        for (ArgHelp help : arghs.values()) {
            sb.append(help.toString());
            sb.append('\n');
        }
        return sb.toString();
    }
}
